<template>
  <div>
    <el-row :gutter="10">
      <fold :span="5" :xs="24" :show.sync='sideshow'>
        <el-card shadow="never">
          <org-tree ref="orgTree" modelType="'dept','community'" @nodeClick="handleNodeClick"
                    @firstNodeClick="handleNodeClick"/>
        </el-card>
      </fold>
      <el-col :span="sideshow ? 19 : 24" :xs="24">
        <el-card shadow="never">
          <div class="dect-main">
            <p class="dect-title">注意事项:</p>
            <div class="dect-content">
              <p class="dect-title">1.月结账之前请确保结账区间内的交款记录都已审核。</p>
              <p class="dect-title">2.月结账以后，交款记录不可反审核，如需反审核，可以先执行反结账操作后再进行反审核。</p>
              <p class="dect-title">3.客户可以灵活规定月结账的日期段，但此日期段不能为已月结的日期段，同时月结账结束日期不能小于月结账开始日期。</p>
              <p class="dect-title">4.系统每年最多只允许做12次月结账。</p>
            </div>
          </div>
          <div class="form-main">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain size="mini" @click="handlePayment('month_payment')"
                           :class="{'btn-pitch-on':activeName=='month_payment'?true:false}" >
                  月结账
                </el-button>
              </el-col>
              <!--<el-col :span="1.5">-->
              <!--<el-button type="primary" plain size="mini" @click="handlePayment('year_payment')" :class="{'btn-pitch-on':activeName=='year_payment'?true:false}">-->
              <!--年结账-->
              <!--</el-button>-->
              <!--</el-col>-->
              <el-col :span="1.5">
                <el-button type="primary" plain size="mini" @click="handleBackPayment"
                           :class="{'btn-pitch-on':activeName=='back_payment'?true:false}" v-hasPermi="['payfee:fiscalRecord:backFiscal']">
                  反结账
                </el-button>
              </el-col>
            </el-row>


            <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="margin-top: 40px;">
              <el-form-item label="当前账期" prop="fiscalPeriod">
                <el-date-picker
                  v-model="form.fiscalPeriod"
                  type="month"
                  placeholder="选择月"
                  disabled
                >
                </el-date-picker>
              </el-form-item>
            </el-form>
            <div class="dialog-footer" style="text-align: center;">
              <el-button type="primary" plain v-loading.fullscreen.lock="loading" @click="handelFiscal" v-hasPermi="['payfee:fiscalRecord:fiscal']">结 账</el-button>
              <el-button type="primary" plain  @click="handleFiscalBeforeCheck" v-hasPermi="['payfee:fiscalRecord:fiscalBeforeCheck']">结账前检查</el-button>
              <el-button type="primary" plain @click="handleFiscalRecord" v-hasPermi="['payfee:fiscalRecord:list']">结账记录</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="结账检查" :visible.sync="open" width="960px" append-to-body >
        <div class="dect-content">
          <p class="dect-title">{{currentNode.label}}未生成账单收费项总数[<span style="color: red;font-size: 20px;">{{listData.length}}</span>]</p>
        </div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="24">
          <!-- 查询表单 -->
          <el-form :inline="true" :model="queryParams" ref="queryForm" size="small" label-width="0"
                   class="demo-form-inline" style="height: 40px;float: right;">
            <el-form-item prop="roomId">
              <room-filterable v-model="queryParams.roomId" />
            </el-form-item>
            <el-form-item prop="customName">
              <el-input
                v-model="queryParams.customName"
                placeholder="客户名称"
                clearable
              />
            </el-form-item>
            <el-form-item style="width: 100px;" prop="projectId">
              <el-select
                v-model="queryParams.projectId"
                placeholder="费用类型"
                clearable
              >
                <el-option v-for="item in projectOptions"
                           :key="item.projectId"
                           :label="item.projectType"
                           :value="item.projectId"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="width: 100px;" prop="chargeId">
              <el-select
                v-model="queryParams.chargeId"
                placeholder="收费项目"
                clearable
              >
                <el-option v-for="item in itemOptions"
                           :key="item.chargeId"
                           :label="item.chargeName"
                           :value="item.chargeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"></el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"></el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-table :data="listData" height="400" @selection-change="handleSelectionChange">
        <!--<el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="房间名称" align="left" prop="roomName" />
        <el-table-column label="客户名称" align="left" prop="customName" />
        <el-table-column label="费用类型" align="left" prop="projectId":formatter="projectFormat"/>
        <el-table-column label="收费项目" align="left" prop="chargeId" :formatter="itemFormat"/>
        <el-table-column label="收费标准" align="left" prop="normNames" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <!--<el-button type="primary" plain @click="handleCreateFeeForm" :disabled="!selection.length">生成账单</el-button>-->
        <!--<el-button type="success" plain @click="handleCreateFeeAllForm">一键生成所有账单</el-button>-->
        <el-button type="success" plain @click="handleCreateFeeAllForm" v-hasPermi="['payfee:tollCenter:createFeeForm']" >一键生成所有账单</el-button>
        <el-button @click="cancel">返 回</el-button>
      </div>

    </el-dialog>
    <fiscal-record-list ref="recordRef"/>
    <rule-cost-list ref="costRef"/>
  </div>
</template>

<script>
  import {getCommunity} from "@/api/property/community"
  import { fiscalBeforeCheck,fiscal,backFiscal } from "@/api/payfee/fiscalRecord"
  import { listItem } from "@/api/payfee/item";
  import { listProject} from "@/api/payfee/project";
  import { createFeeForm,selectFeeFormByFiscalPeriod} from "@/api/payfee/tollCenter";
  import FiscalRecordList from "./fiscalRecordList"
  import RuleCostList from "./fiscalFeeDetail";

  export default {
    name: "closeAccounts",
    components:{ FiscalRecordList ,RuleCostList},
    data() {
      return {
        activeName: 'month_payment',
        currentNode: {},
        sideshow: true,
        form: {},
        rules: {
          fiscalPeriod: [
            {required: true, message: "结账年月不能为空", trigger: "blur"}
          ],
        },
        open:false,
        //用来显示的列表集合
        listData:[],
        //历史列表集合
        currentPeriodFeeVos:[],
        //收费项目字典
        itemOptions:[],
        //收费类型字典
        projectOptions:[],
        //选中的列表
        selection:[],
        loading:false,
        queryParams:{
          roomId:null,
          projectId:null,
          chargeId:null,
          customName:null
        },
        communityName:null
      }
    },
    created() {
      this.reset()
      listItem().then(res=>{
        this.itemOptions = res.rows;
      })
      listProject().then(res=>{
        this.projectOptions = res.rows;
      })
    },
    methods: {
      handleNodeClick(node) {
        this.currentNode = node;
        if (node.modelType == 'community') {
          getCommunity(node.id).then(res => {
            this.form.fiscalPeriod = res.data.fiscalPeriod
            this.form.communityId = res.data.id
            this.communityName = res.data.communityName
          })
        }
      },
      reset() {
        this.form = {
          fiscalType: 'month_payment', //结账类型 --- 月结账|年结账
          fiscalPeriod: null,//结账日期
          communityId:null,
          monthBeginTime: null,//月结账开始日期
          monthFinishTime: null,//月结账结束日期
        }
      },
      // 收费项目字典翻译
      itemFormat(row, column) {
        let index = this.itemOptions.findIndex(x=>x.chargeId == row.chargeId);
        if(index != -1){
          return this.itemOptions[index].chargeName
        }
        return '';
      },
      // 收费类型字典翻译
      projectFormat(row, column) {
        let index = this.projectOptions.findIndex(x=>x.projectId == row.projectId);
        if(index != -1){
          return this.projectOptions[index].projectType
        }
        return '';
      },
      handlePayment(type) {
        this.form.fiscalType = type
        this.activeName = type
      },
      //反结账
      handleBackPayment() {
        let form = this.form
        form.fiscalType = 'back_payment'
        let fiscalPeriod = this.form.fiscalPeriod+"-01"
        //上一个月的日期
        let theDate = this.$utils.toDateString(this.getNextMonthDay(fiscalPeriod,-1),'yyyy-MM')
        this.$confirm(`是否要把小区[${this.communityName}]反结账费用期间到[${theDate}]`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=>{
          return backFiscal(form);
        }).then((res) => {
          this.msgSuccess("反结账成功")
          this.form.fiscalPeriod = res.data.fiscalPeriod
        }).catch(() => {
        });
      },
      //结账
      handelFiscal(){
        let me = this
        //月结账
        if (this.activeName =='month_payment'){
          this.$confirm(`小区[${this.communityName}]月结账,确认无误之后请点击确认按钮。`, "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(()=>{
            this.handleFiscalBeforeCheck(()=>{
              fiscal(this.form).then(res=>{
                this.msgSuccess("结账成功")
                this.form.fiscalPeriod = res.data.fiscalPeriod
              })
            });
          }).catch(() => {
          });
        }
      },
      handleFiscalBeforeCheck(callback) {
        if (this.currentNode.modelType == 'community') {
          let param = {
            fiscalPeriod: this.form.fiscalPeriod,
            communityId: this.currentNode.id
          }
          this.loading = true
          fiscalBeforeCheck(param).then(res => {
            this.currentPeriodFeeVos = res.data.currentPeriodFeeVos
            if(this.currentPeriodFeeVos.length > 0){
              this.open = true
              this.listData = this.currentPeriodFeeVos
            }else{
              if(callback && callback instanceof Function){
                callback()
              }
              this.msgSuccess("检查通过")
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.msgWarning("请选择需要结账的小区")
        }

      },
      cancel(){
        this.open = false
      },
      handleSelectionChange(selection) {
        this.selection = selection
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleQuery() {
        this.listData = this.currentPeriodFeeVos.filter(row=>{
          let roomFlag = true,projectFalg = true,chargeFlag = true,customNameFlag = true
          if(this.queryParams.roomId){
            roomFlag = row.roomId == this.queryParams.roomId
          }
          if(this.queryParams.projectId){
            projectFalg = row.projectId == this.queryParams.projectId
          }
          if(this.queryParams.chargeId){
            chargeFlag = row.chargeId == this.queryParams.chargeId
          }
          if(this.queryParams.customName){
            customNameFlag = row.customName.includes(this.queryParams.customName)
          }
          return roomFlag&&projectFalg&&chargeFlag&&customNameFlag
        })
      },
      //生成账单
      handleCreateFeeForm(){
        if(this.selection.length > 0){
          let roomNormIds = this.selection.map(item => item.roomNormId)
          createFeeForm({fiscalPeriod:this.form.fiscalPeriod,communityId: this.currentNode.id,roomNormIds:roomNormIds}).then(res=>{
            this.msgSuccess("创建账单成功")
            this.open = false
          })
        }else{
          this.msgWarning("请选择需要创建账单的房屋收费标准。")
        }

      },
      //一键生成所有账单
      handleCreateFeeAllForm(){
        createFeeForm({fiscalPeriod:this.form.fiscalPeriod,communityId: this.currentNode.id}).then(res=>{
          this.msgSuccess("一键生成所有账单的时间可能较长,账单生成之后会及时通知到你!")
          this.open = false
        })
      },
      //结账记录
      handleFiscalRecord(){
        if (this.currentNode.modelType == 'community') {
          this.$refs.recordRef.show({currentNode:this.currentNode})
        } else {
          this.msgWarning("请选择需要结账的小区")
        }
      }
    }
  }
</script>

<style scoped>

  .dect-main {
    color: red;
  }

  .dect-content {
    margin-left: 10px;
  }

  .form-main {
    width: 30rem;
    margin-top: 40px;
  }

  .btn-pitch-on {
    background-color: #1890ff;
    color: #FFFFFF;
  }
  ::v-deep .el-dialog__body {
    padding: 10px 20px;
  }
</style>
